<template>
  <s-clean-layout title="纪念日管理">
    <view class="memorial-container">
      <!-- 搜索框 -->
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input 
          class="search-input" 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索联系人、纪念日、日期" 
          @input="handleSearch"
        />
      </view>

      <view class="empty-tip" v-if="filteredMemorialData.length === 0">
        <image class="empty-icon" src="/static/data-empty.png" mode="aspectFit"></image>
        <text class="empty-text">{{ searchKeyword ? '未找到相关纪念日' : '暂无纪念日数据' }}</text>
      </view>

      <!-- 纪念日卡片列表 -->
      <view 
        class="memorial-card" 
        v-for="(item, index) in filteredMemorialData" 
        :key="item.id"
        @tap="onMemorialClick(item)"
      >
        <view class="memorial-header">
          <view class="user-info">
            <image v-if="item.avatarUrl" class="user-avatar" :src="item.avatarUrl" mode="aspectFill" @error="handleImageError(item)"></image>
            <text class="user-name" :class="{'no-avatar': !item.avatarUrl}">{{ item.contactName }}</text>
          </view>
          <view class="title-info">
            <uni-icons class="title-icon" :type="getIconType(item.title)" size="20" color="#B388FF"></uni-icons>
            <text class="memorial-title">{{ item.title }}</text>
            <uni-icons class="memorial-bell" type="notification" size="18" color="#999"></uni-icons>
          </view>
        </view>
        
        <view class="memorial-content">
          <view class="date-info">
            <text class="date-text">{{ item.date }} {{ getWeekDay(item.date) }}</text>
            <text class="lunar-text" v-if="item.lunarDate">{{ item.lunarDate }}</text>
          </view>
          
          <view class="count-cards">
            <view class="count-card pink">
              <text class="count-label">倒计时</text>
              <text class="count-number">{{ item.countdown }}</text>
            </view>
            
            <view class="count-card purple">
              <text class="count-label">{{ item.anniversaryLabel || '周年' }}</text>
              <text class="count-number">{{ item.anniversary }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 添加悬浮按钮 -->
      <view class="add-button" @tap="addMemorial">
        <uni-icons type="plusempty" size="24" color="#FFFFFF"></uni-icons>
      </view>
      
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import MemorialApi from '@/pages/contact/api/importday';

// 搜索关键词
const searchKeyword = ref('');

// 纪念日数据
const displayMemorialData = ref([]);
const isLoading = ref(false);

// 过滤后的纪念日数据
const filteredMemorialData = computed(() => {
  if (!searchKeyword.value) return displayMemorialData.value;
  
  const keyword = searchKeyword.value.toLowerCase();
  return displayMemorialData.value.filter(item => {
    return (
      item.contactName.toLowerCase().includes(keyword) ||
      item.title.toLowerCase().includes(keyword) ||
      item.date.includes(keyword) ||
      (item.lunarDate && item.lunarDate.includes(keyword))
    );
  });
});

// 处理搜索
const handleSearch = () => {
  // 搜索逻辑已经在 computed 中实现
};

// 加载纪念日数据
const loadMemorialData = async () => {
  if (isLoading.value) return;
  
  try {
    isLoading.value = true;
    uni.showLoading({ title: '加载中' });
    
    const res = await MemorialApi.queryImportDays({});
    
    if (res.code === 0 && res.data) {
      displayMemorialData.value = res.data.map(item => {
        // 计算倒计时天数
        const today = new Date();
        const importDate = new Date(item.importDate);
        const thisYearDate = new Date(today.getFullYear(), importDate.getMonth(), importDate.getDate());
        
        // 如果今年的日期已过，则计算到明年的日期
        if (thisYearDate < today) {
          thisYearDate.setFullYear(today.getFullYear() + 1);
        }
        
        const diffTime = thisYearDate.getTime() - today.getTime();
        const countdown = Math.ceil(diffTime / (1000 * 3600 * 24));
        
        // 计算周年数
        const years = today.getFullYear() - importDate.getFullYear();
        const anniversary = years > 0 ? `${years}周年` : '首年';
        
        // 格式化日期
        const formatDate = date => {
          const d = new Date(date);
          return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
        };
        
        return {
          id: item.id,
          title: item.dayName,
          date: formatDate(item.importDate),
          lunarDate: item.lunarDate || '',
          description: item.remark || '',
          type: item.dayName.includes('生日') ? 'birthday' : 'memorial',
          countdown: countdown,
          anniversary: anniversary,
          anniversaryLabel: '周年',
          contactId: item.contactId,
          contactName: item.contactName || '未知联系人',
          avatarUrl: item.avatarUrl || ''
        };
      });
    } else {
      uni.showToast({
        title: res.msg || '获取纪念日列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取纪念日列表失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
    uni.hideLoading();
  }
};

// 点击纪念日卡片，跳转到纪念日编辑页面
const onMemorialClick = (memorial) => {
  uni.navigateTo({
    url: `/pages/contact/memorial-edit?id=${memorial.id}&contactId=${memorial.contactId}&mode=edit&contactName=${encodeURIComponent(memorial.contactName)}&contactImg=${encodeURIComponent(memorial.avatarUrl || '')}`
  });
};

// 处理图片加载错误
const handleImageError = (item) => {
  item.avatarUrl = '';
};

// 获取日期对应的星期几
const getWeekDay = (dateString) => {
  if (!dateString) return '';
  
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const date = new Date(dateString);
  
  if (isNaN(date.getTime())) return '';
  
  return weekDays[date.getDay()];
};

// 根据纪念日标题获取对应图标
const getIconType = (title) => {
  const iconMap = {
    '生日': 'gift',
    '结婚纪念日': 'heart',
    '入职纪念': 'medal'
  };
  
  return iconMap[title] || 'calendar';
};

// 页面显示时加载数据
onShow(() => {
  loadMemorialData();
});

// 添加新纪念日
const addMemorial = () => {
  uni.navigateTo({
    url: `/pages/contact/memorial-edit?mode=add`
  });
};

onPullDownRefresh(() => {
  loadMemorialData().finally(() => {
    uni.stopPullDownRefresh();
  });
});
</script>

<style lang="scss" scoped>
.memorial-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100%;
  position: relative;  /* 添加相对定位，作为悬浮按钮的参考 */
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #FFFFFF;
  border-radius: 8rpx;
  padding: 16rpx 20rpx;
  margin-bottom: 20rpx;
  
  .search-input {
    flex: 1;
    margin-left: 16rpx;
    font-size: 14px;
    color: #333;
    
    &::placeholder {
      color: #999;
    }
  }
}

.memorial-card {
  margin-bottom: 20rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.memorial-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-right: 16rpx;
}

.user-name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.no-avatar {
  margin-left: 0;
}

.title-info {
  display: flex;
  align-items: center;
}

.title-icon {
  margin-right: 10rpx;
}

.memorial-title {
  font-size: 16px;
  font-weight: 500;
  color: #B388FF;
  margin-right: 10rpx;
}

.memorial-bell {
  padding: 6rpx;
}

.memorial-content {
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-info {
  display: flex;
  flex-direction: column;
}

.date-text {
  font-size: 16px;
  color: #333;
  margin-bottom: 8rpx;
}

.lunar-text {
  font-size: 14px;
  color: #999;
  margin-top: 4rpx;
}

.count-cards {
  display: flex;
  gap: 16rpx;
}

.count-card {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.count-card.pink {
  background-color: #FF9E9E;
}

.count-card.purple {
  background-color: #B388FF;
}

.count-label {
  font-size: 12px;
  color: #fff;
  margin-bottom: 8rpx;
}

.count-number {
  font-size: 18px;
  font-weight: 600;
  color: #fff;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 添加悬浮按钮样式 */
.add-button {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #B388FF;  /* 使用紫色主题，与纪念日页面风格一致 */
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(179, 136, 255, 0.3);
  z-index: 10;
}
</style>